package cn.ydxiaoshuai.modules.quartz.job;

import cn.ydxiaoshuai.common.constant.ApiCodeConts;
import cn.ydxiaoshuai.common.util.RedisUtil;
import cn.ydxiaoshuai.modules.entity.LiteApiLog;
import cn.ydxiaoshuai.modules.service.ILiteApiLogService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author xavier
 * @className ApiLogJob
 * @Description 接口日志
 * @Date 2020/9/8-15:51
 **/
@Slf4j
public class LiteApiLogJob implements Job {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ILiteApiLogService liteApiLogService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        liteApiLog();
    }
    /**
     * @author xavier
     * @Description 请求日志保存数据库
     * @Date  2020年9月11日
     **/
    private void liteApiLog() {
        if (redisUtil.hasKey(ApiCodeConts.API_LOG_LIST_KEY)) {
            long size = redisUtil.lGetListSize(ApiCodeConts.API_LOG_LIST_KEY);
            log.info("接口请求日志持久化操作:{}", size);
            //日志对象
            LiteApiLog liteApiLog;
            if (size > 0) {
                List<Object> objects = redisUtil.lGet(ApiCodeConts.API_LOG_LIST_KEY, 0, -1);
                //防止有问题 一个一个循环插入
                for (int i = 0; i < objects.size(); i++) {
                    //防止出错先Object
                    liteApiLog = (LiteApiLog)objects.get(i);
                    //先删除
                    redisUtil.lRemove(ApiCodeConts.API_LOG_LIST_KEY, 1, liteApiLog);
                    //再保存
                    liteApiLogService.save(liteApiLog);
                }
            }
        }
    }

}
